/*
* Copyright 2010 Pavel Kozhin 
*
* Licensed under the Apache License, Version 2.0 (the "License"); 
* you may not use this file except in compliance with the License. 
* You may obtain a copy of the License at 
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software 
* distributed  under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
* See the License for the specific language governing permissions and 
* limitations under the License.
*
* Author: Pavel Kozhin.
*/

package org.etherframework.core
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.EventPhase;
	import flash.utils.describeType;
	
	import mx.core.IFlexDisplayObject;
	import mx.core.IMXMLObject;
	import mx.core.Singleton;
	import mx.core.mx_internal;
	
	import org.etherframework.behaviour.Behaviour;
	import org.etherframework.behaviour.BehaviourController;
	import org.etherframework.dependency.Dependency;
	import org.etherframework.dependency.DependencyController;
	import org.etherframework.metadata.Metadata;
	import org.etherframework.metadata.MetadataController;
	import org.etherframework.wire.Wire;
	import org.etherframework.wire.WireController;
	
	use namespace mx_internal;
	
	[Event(name="register", type="flash.events.Event")]
	
	[Event(name="unregister", type="flash.events.Event")]
	
	public class Controller extends EventDispatcher implements IController, IMXMLObject
	{
		private var descriptor:XML;
		
		private var isInitialized:Boolean = false;
		
		private var eventPriority:int = 200;
		
		public function initialized(document:Object, id:String):void
		{
			_id = id;
			_host = document as IFlexDisplayObject;
			
			if (_host && !isInitialized)
			{
				isInitialized = true;
				_host.addEventListener(Event.ADDED, hostAddedHandler, false, 1000);
				_content = initContent();
				createParts();
			}
		}
		
		private var _id:String;

		public function get id():String
		{
			return _id;
		}
		
		private var _host:IFlexDisplayObject;
		
		public function get host():IFlexDisplayObject
		{
			return _host;
		}
		
		private var _content:Array;
		
		public function get content():Array
		{
			return _content;
		}
		
		private var _metadata:IControllerPart;
		
		public function get metadata():IControllerPart
		{
			return _metadata;
		}
		
		private var _dependency:IControllerPart;
		
		public function get dependency():IControllerPart
		{
			return _dependency;
		}
		
		private var _wire:IControllerPart;
		
		public function get wire():IControllerPart
		{
			return _wire;
		}
		
		private var _feature:IControllerPart;
		
		public function get feature():IControllerPart
		{
			return _feature;
		}
		
		private function hostAddedHandler(event:Event):void
		{
			if (event.eventPhase == EventPhase.AT_TARGET)
			{
				_host.removeEventListener(Event.ADDED, hostAddedHandler);
				_host.addEventListener(Event.REMOVED_FROM_STAGE, hostRemovedFromStageHandler);
				
				var em:IEtherManager = 
					IEtherManager(Singleton.getInstance("org.etherframework.core::IEtherManager"));
				em.register(this);
			}
		}
		
		private function hostRemovedFromStageHandler(event:Event):void
		{
			_host.removeEventListener(Event.REMOVED_FROM_STAGE, hostRemovedFromStageHandler);
			_host.addEventListener(Event.ADDED, hostAddedHandler, false, eventPriority);
			
			var em:IEtherManager = 
				IEtherManager(Singleton.getInstance("org.etherframework.core::IEtherManager"));
			em.unregister(this);
		}
		
		protected function createParts():void
		{
			var metadata:Array = [];
			var dependency:Array = [];
			var	wire:Array = [];
			var feature:Array = [];
			var item:Object;
			var contentLen:int = _content.length;
			
			for (var i:int = 0; i < contentLen; ++i)
			{
				item = _content[i];
				
				if (item is Dependency)
				{
					dependency.push(item);
				} 
				else if (item is Metadata)
				{
					metadata.push(item);
				}
				else if (item is Wire)
				{
					wire.push(item);
				}
				else if (item is Behaviour)
				{
					feature.push(item);
				}
			}
			
			_metadata = new MetadataController(metadata);
			_dependency = new DependencyController(dependency);
			_wire = new WireController(wire);
			_feature = new BehaviourController(feature);
		}
		
		protected function initContent():Array
		{
			var result:Array = [];
			
			if (!descriptor)
				descriptor = describeType(this);
			
			var i:int;
			var obj:Object;
			var accessName:String = "readwrite";
			var variables:XMLList = descriptor.variable.@name;
			var variablesLen:int = variables.length();
			var accessors:XMLList = descriptor.accessor.(@access == accessName).@name;
			var accessorsLen:int = accessors.length();
			
			for (i = 0; i < accessorsLen; ++i) 
			{
				obj = this[accessors[i]];
				result.push(obj);
			}
			
			for (i = 0; i < variablesLen; ++i)
			{
				obj = this[variables[i]];
				result.push(obj);
			}
			
			return result;
		}
		
	}
}